/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "util.h"

#include <stdlib.h>
#include <string.h>
#include "hi_debug.h"

int IntZoomTo(int n, double rate, double rateMin, double rateMax) {
    HI_ASSERT(rateMin < 1 && rateMax > 1);

    if (!rateMin) {
        HI_ASSERT(rateMin);
        return n;
    } else {
        int ret;
        if (rate > rateMax) {
            ret = n * (int) rateMax;
        } else if (rate < rateMin) {
            ret = n / (int) (1 / rateMin);
        } else {
            ret = (int) (n * rate);
        }
        return ret < 1 ? 1 : ret;
    }
}

void RectBoxTran(RectBox* box, int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
    HI_ASSERT(box && srcWidth && srcHeight);
    box->xmin = box->xmin * dstWidth / srcWidth * 2 / 2;
    box->xmax = box->xmax * dstWidth / srcWidth * 2 / 2;
    box->ymin = box->ymin * dstHeight / srcHeight * 2 / 2;
    box->ymax = box->ymax * dstHeight / srcHeight * 2 / 2;
}

int HiStrxfrm(char *s1, char *s2, int n) {
    int i;

    for (i = 0; (i < n - 1) && s2[i]; i++) {
        s1[i] = s2[i];
    }
    s1[i] = 0;
    return i;
}

void RecurMutexInit(pthread_mutex_t* mutex) {
    HI_ASSERT(mutex);
    pthread_mutexattr_t attr;
    int res;

    res = pthread_mutexattr_init(&attr);
    HI_ASSERT(!res);

    res = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    HI_ASSERT(!res);
    res = pthread_mutex_init(mutex, &attr);
    HI_ASSERT(!res);

    pthread_mutexattr_destroy(&attr);
}
